/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 */

package com.hyyt.shopjsp.wxmg.fans.controller;

import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.wxmg.fans.pojo.WxFansGroup;
import com.hyyt.shopjsp.wxmg.fans.pojo.WxFansUserInfo;
import com.hyyt.shopjsp.wxmg.fans.service.IWxFansGroupService;
import com.hyyt.shopjsp.wxmg.fans.service.IWxFansUserInfoService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Liu Ling on 2017/11/10 0010.
 *
 * 粉丝分组
 */
@Controller
@RequestMapping("/back/wx/fansGroup")
public class WxFansGroupController  extends BaseController {

    private Logger logger = Logger.getLogger(WxFansGroupController.class);
    private String basePath = "/back/wxmg/fansGroup/";

    @Resource
    private IWxFansGroupService wxFansGroupService;
    @Resource
    private IWxFansUserInfoService wxFansUserInfoService;

    /**
     * 进入粉丝分组页面
     *
     * @return 返回到指定页面
     */
    @RequestMapping("gotoFansGroupPage")
    public String gotoFansGroupPage (){
        return basePath + "fansGroupList";
    }

    /**
     *查询所有粉丝分组列表
     *
     * @param name 组名称
     * @param isValid 是否有效
     * @param createBeginTime 创建开始时间
     * @param createEndTime 创建结束时间
     * @param page 分页
     * @param response 返回结果集
     */
    @RequestMapping(value = "listFansGroup",method = RequestMethod.POST)
    @ResponseBody
    public void listFansGroup(String name, String isValid, String createBeginTime, String createEndTime, Page page, HttpServletResponse response){
        Map<String,Object> param = new HashMap<>();
        if (Utils.objectIsNotEmpty(name)) {
            param.put("name", name.trim());
        }
        if (Utils.objectIsNotEmpty(isValid)) {
            param.put("isValid", isValid);
        }
        if (Utils.objectIsNotEmpty(createBeginTime)) {
            param.put("createBeginTime", createBeginTime);
        }
        if (Utils.objectIsNotEmpty(createEndTime)) {
            param.put("createEndTime", createEndTime);
        }
        int totalRecordCount = wxFansGroupService.countWxFansGroup(param);
        param.put("sortColumns","fansGroupId desc");
        page.setPageInfo(page.getPageSize(),totalRecordCount,page.getCurrentPage());
        List<WxFansGroup> list = wxFansGroupService.queryWxFansGroup(param,page.getPageRecordBeginIndex(),page.getPageSize());
        param.clear();
        param.put("total",totalRecordCount);
        param.put("rows",list);
        ResultMsg.create(param,response);
    }

    /**
     * 根据id获得粉丝分组对象
     * @param fansGroupId 粉丝分组id
     * @return
     */
    @RequestMapping(value = "getFansGroupObject",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg getFansGroupObject(Integer fansGroupId){
        if (Utils.objectIsNotEmpty(fansGroupId)){
            WxFansGroup wxFansGroup = wxFansGroupService.loadWxFansGroup(fansGroupId);
            return ResultMsg.create(true,null, FastJsonUtils.toJSONString(wxFansGroup));
        }else{
            return ResultMsg.create(false);
        }
    }

    /**
     * 保存或者修改粉丝分组
     * @param fansGroupId 粉丝分组id
     * @param wxFansGroup 粉丝分组对象
     * @return 返回布尔值
     */
    @RequestMapping(value = "saveOrUpdateFansGroup",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveOrUpdateFansGroup(Integer fansGroupId,WxFansGroup wxFansGroup){
        if (Utils.objectIsNotEmpty(wxFansGroup)){
            if (Utils.objectIsEmpty(wxFansGroup.getFansGroupId())){
                // TODO
                /*String ids="";
                List<FansGroup> fansGroupList=selectGroup(publicNoInfo,access_token);//查找所有
                for(FansGroup fg:fansGroupList){
                    ids=ids+fg.getId()+",";
                }
                String[] id=ids.split(",");
                int max=Integer.parseInt(id[0]);
                for(int i=1;i<id.length;i++){
                    int a=Integer.parseInt(id[i]);
                    if(max<a){
                        max=a;
                    }
                }*/
                wxFansGroup.setPublicNumberId(1);
                wxFansGroup.setCount(0);
                wxFansGroup.setIsValid(0);
                wxFansGroup.setCreateTime(new Timestamp(System.currentTimeMillis()));
                wxFansGroupService.saveWxFansGroup(wxFansGroup);
            }else if (Utils.objectIsNotEmpty(fansGroupId)){
                WxFansGroup wxFansGroup1=wxFansGroupService.loadWxFansGroup(fansGroupId);
                wxFansGroup1.setName(wxFansGroup.getName());
                wxFansGroupService.updateWxFansGroup(wxFansGroup1);
            }
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     * 根据id删除粉丝分组
     * @param fansGroupId 粉丝分组id
     * @return 返回布尔值
     */
    @RequestMapping(value = "deleteFansGroup",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg deleteFansGroup(Integer fansGroupId){
        if (Utils.objectIsNotEmpty(fansGroupId)){
            Map<String,Object> param = new HashMap<>();
            param.put("fansGroupId",fansGroupId);
            List<WxFansUserInfo> list=wxFansUserInfoService.queryWxFansUserInfo(param);
            for (WxFansUserInfo wxFansUserInfo : list){
                wxFansUserInfo.setFansGroupId(0);//删除了粉丝分组需要对相对应的粉丝用户表中的粉丝分组id进行重新复赋值
                wxFansUserInfoService.updateWxFansUserInfo(wxFansUserInfo);
            }
            wxFansGroupService.deleteWxFansGroup(fansGroupId);
            return ResultMsg.create(true);
        }else{
            return ResultMsg.create(false);
        }
    }

    /**
     * 更改粉丝分组有效状态
     * @param fansGroupId 粉丝分组id
     * @param isValid 是否有效
     * @return 返回布尔值
     */
    @RequestMapping(value = "changeFansGroupState",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg changeFansGroupState(Integer fansGroupId,Integer isValid){
        if (Utils.objectIsNotEmpty(fansGroupId)){
            WxFansGroup wxFansGroup=wxFansGroupService.loadWxFansGroup(fansGroupId);
            wxFansGroup.setIsValid(isValid);
            wxFansGroupService.updateWxFansGroup(wxFansGroup);
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }

    /**
     *查询未分组粉丝用户信息列表
     *
     * @param nickName 昵称
     * @param subscribeBeginTime 关注开始时间
     * @param subscribeEndTime 关注结束时间
     * @param page 分页
     * @param response 返回结果集
     */
    @RequestMapping(value = "UnGroupedFansList",method = RequestMethod.POST)
    @ResponseBody
    public void UnGroupedFansList(String nickName, String subscribeBeginTime, String subscribeEndTime, Page page, HttpServletResponse response) throws ParseException {
        Map<String,Object> param = new HashMap<>();
        if (Utils.objectIsNotEmpty(nickName)) {
            param.put("nickName", nickName.trim());
        }
        if(Utils.objectIsNotEmpty(subscribeBeginTime)){
            param.put("subscribeBeginTime",subscribeBeginTime);
        }
        if(Utils.objectIsNotEmpty(subscribeEndTime)){
            param.put("subscribeEndTime",subscribeEndTime);
        }
        int totalRecordCount = wxFansUserInfoService.countUnGroupedFansList(param);
        param.put("sortColumns","userId desc");
        page.setPageInfo(page.getPageSize(),totalRecordCount,page.getCurrentPage());
        List<Map<String,Object>> list = wxFansUserInfoService.queryUnGroupedFansList(param,page.getPageRecordBeginIndex(),page.getPageSize());
        param.clear();
        param.put("total",totalRecordCount);
        param.put("rows",list);
        ResultMsg.create(param,response);
    }

    /**
     * 新增粉丝用户
     * @param userId 粉丝用户信息id
     * @param fansGroupId 粉丝分组id
     * @param count 人数
     * @return 返回布尔值
     */
    @RequestMapping(value = "addFansUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg addFansUserInfo(Integer userId,Integer fansGroupId,Integer count){
        // TODO
        /*boolean isSuccess=false;
        JSONObject jo = new JSONObject();
        fansUserInfo = (FansUserInfo) fansUserInfoService.getObjectByParams("where o.userId="+id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("openid", fansUserInfo.getUserOpenId());
        jsonObject.accumulate("to_groupid", fansGroupId);
        //System.out.println("***********jsonObject.toString() ="+jsonObject.toString());
        PublicNoInfo publicNoInfo =	(PublicNoInfo)servletContext.getAttribute("publicNoInfo");
        Map<?,?> pMap = (Map<?,?>)servletContext.getAttribute("accessTokens");
        String access_token = (String) pMap.get(publicNoInfo.getToUserName());
        String strJson = WxGroupManager.postSubmit(access_token, jsonObject.toString(), "moveUserGroup");
        //System.out.println("***********strJson="+strJson);
        String globalReturnCodeStr = RedisDataReadUtil.getRedisValue(StringStaticKey.WX_GLOBAL_RETURN_CODE);
        List<WxGlobalReturnCode> globalReturnCodeList = FastJsonUtils.toList(globalReturnCodeStr, WxGlobalReturnCode.class);
        String backMessage = WxGlobalReturnCodeUtil.getGlobalReturnCode(strJson,globalReturnCodeList);//判断返回值是否为错误值*/
        if (Utils.objectIsNotEmpty(userId)&&Utils.objectIsNotEmpty(fansGroupId)&&Utils.objectIsNotEmpty(count)){
            WxFansGroup wxFansGroup=wxFansGroupService.loadWxFansGroup(fansGroupId);
            WxFansUserInfo wxFansUserInfo=wxFansUserInfoService.loadWxFansUserInfo(userId);
            wxFansUserInfo.setFansGroupId(wxFansGroup.getFansGroupId());//粉丝分组中如果新加入了粉丝需要在粉丝用户表中改变粉丝分组id值
            wxFansUserInfoService.updateWxFansUserInfo(wxFansUserInfo);
            Map<String,Object> param = new HashMap<>();
            param.put("fansGroupId",fansGroupId);
            wxFansGroup.setCount(wxFansUserInfoService.countWxFansUserInfo(param));//粉丝分组中如果新加入了粉丝需要在人数上发生变化
            wxFansGroupService.updateWxFansGroup(wxFansGroup);
            return ResultMsg.create(true);
        }else {
            return ResultMsg.create(false);
        }
    }
}
